import { Body, Inject, Post } from '@midwayjs/decorator';
import { DemoGoodsEntity } from '../../entity/goods';
import { BaseController, CoolController } from '@cool-midway/core';
import { Context } from 'vm';
import { InjectEntityModel } from '@midwayjs/orm';
import { getConnection, Repository, Timestamp, Brackets } from 'typeorm';

import xlsx from 'node-xlsx';
import * as dayjs from 'dayjs'
import * as _ from 'lodash'

/**
 * 测试
 */
@CoolController({
	api: ['add', 'delete', 'update', 'info', 'page', 'list'],
	entity: DemoGoodsEntity,
	insertParam: async (ctx: Context) => {

	},
	// 分页查询配置
	pageQueryOp: {

		fieldEq: ['departmentId', 'state'],
		keyWordLikeFields: ['name', 'idnumber'],
		where: async (ctx: Context) => {

			if (ctx.admin.roleLabel == 'admin' || ctx.admin.roleLabel == 'system') {
				return []
			} else {
				return [
					['state = :price', { price: '0' }],
				]
			}
		},
		// addOrderBy: {
		// 	createTime: 'desc'
		// }
	},
})
export class CoolGoodsController extends BaseController {
	@Inject()
	ctx: Context;
	@InjectEntityModel(DemoGoodsEntity)
	demoGoodsEntity: Repository<DemoGoodsEntity>;

	/**
	 * 获取新增数量
	 */
	@Post('/getnew')
	async getnew() {
		const body = this.ctx.request.body;
		const res = await this.demoGoodsEntity.createQueryBuilder()
			.where(new Brackets(qb => {
				qb.where('departmentId=' + body.departmentId);
				qb.andWhere("isNew=1");

			}))
			.getMany()
		return this.ok(res);
	}
	/**
	 * 更新新增
	 */
	@Post('/resetNew')
	async reset(
		@Body('ids') ids: []
	) {
		await this.demoGoodsEntity.createQueryBuilder()
			.update()
			.set({ isNew: 0 })
			.where('id in (:ids)', { ids })
			.execute();
		return this.ok();
	}

	/**
	 * 减员
	 */
	@Post('/minus')
	async minus(
		@Body('minusDate') minusDate: Timestamp,
		@Body('ids') ids: []
	) {
		await this.demoGoodsEntity.createQueryBuilder()
			.update()
			.set({ minusDate: minusDate, state: 9 })
			.where('id in (:ids)', { ids })
			.execute();
		return this.ok();
	}

	/**
	 * 导出
	 */
	@Post('/export')
	async export() {
		const body = this.ctx.request.body;
		const res = await this.demoGoodsEntity.createQueryBuilder()
			.where(new Brackets(qb => {
				qb.where('departmentId=' + body.departmentId);
				if (body.type == '2') {
					qb.andWhere('plusDate BETWEEN :start AND :end', {
						start: body.datespan[0],
						end: body.datespan[1]
					});
					qb.andWhere('minusDate is NULL');
				} else if (body.type == '3') {
					qb.andWhere('minusDate BETWEEN :start AND :end', {
						start: body.datespan[0],
						end: body.datespan[1]
					});
				}
			}))
			.orderBy("id", "ASC")
			.getMany()
		const data = [
			["序号", "姓名", "性别", "证件类型", "身份证号", "具体工种", "方案", "增员日期", "减员日期"]
		];
		const genderDict = { 1: '男', 0: '女', 2: '未知' };
		res.forEach((item, index) => {
			data.push([index + 1, item.name, genderDict[item.gender], item.idType, item.idnumber, item.type, item.plan,
			item.plusDate ? dayjs(item.plusDate).format('YYYY-MM-DD') : '',
			item.minusDate ? dayjs(item.minusDate).format('YYYY-MM-DD') : ''])
		})

		const result = [{ name: "成员", data: data, options: {} }]
		const buffer = xlsx.build(result);
		this.ctx.status = 200;
		this.ctx.body = buffer;
	}

	/**
	 * 导入
	 */
	@Post("/import")
	async import() {
		const file = this.baseCtx.request.ctx.files[0];
		const departmentId = this.baseCtx.request.ctx.fields.departmentId;
		const data = xlsx.parse(file.data);

		const users = data.length > 0 ? data[0].data : []
		const _users = users.filter((element: [], index) => {
			if ([0, 1, 2, 3].includes(index)) {
				return false;
			} else {
				if (element.length > 10) {
					return true;
				} else {
					return false;
				}
			}
		})
		const insertUsers = _users.map((item) => {
			let gender2 = '2', plusDate = '', minusDate = '', birthday = ''
			if (_.trim(item[2]).includes('男')) {
				gender2 = '1'
			}
			if (_.trim(item[2]).includes('女')) {
				gender2 = '0'
			}
			if (item[10]) {
				plusDate = dayjs(new Date(1900, 0, item[10] - 1)).format('YYYY-MM-DD HH:mm:ss')
			}
			if (item[9]) {
				minusDate = dayjs(new Date(1900, 0, item[9] - 1)).format('YYYY-MM-DD HH:mm:ss')
			}
			if (item[5]) {
				//birthday = dayjs(new Date(1900, 0, item[5] - 1)).format('YYYY-MM-DD HH:mm:ss')
			}
			return {
				departmentId: departmentId,
				name: _.trim(item[1]),
				gender: gender2,
				idType: _.trim(item[3]),
				idnumber: _.trim(item[4]),
				birthday: birthday,
				age: _.trim(item[6]),
				type: _.trim(item[7]),
				plan: _.trim(item[8]),
				plusDate: plusDate,
				minusDate: minusDate,
				premium: 0.00,
				state: 0
			}
		})
		for (let item of insertUsers) {
			const exists = await this.demoGoodsEntity.findOne({
				idnumber: item.idnumber
			});
			if (!_.isEmpty(exists)) {
				await getConnection()
					.createQueryBuilder()
					.update(DemoGoodsEntity)
					.set(item)
					.where("idnumber = :idnumber", { idnumber: item.idnumber })
					.execute();
			} else {
				await getConnection()
					.createQueryBuilder()
					.insert()
					.into(DemoGoodsEntity)
					.values([item])
					.execute();
			}
		}


		return this.ok(insertUsers);
	}
}
